package thread;
//复习  myblockingqueueu(生产者消费者模型) 看ThreadDemo22 来进行复习
class MyBlockingQueue1{
    private int tail;
    private int head;
    private int size;
    private String[] elems;
    private Object locker = new Object();
    public MyBlockingQueue1(int capacity){
        this.elems = new String[capacity];
    }
    public void put(String elem) throws InterruptedException {
        synchronized (locker){
            while(size >= elems.length){
                locker.wait();
            }
            elems[tail] = elem;
            tail++;
            if(tail >= elems.length){
                tail = 0;
            }
            size++;
            locker.notify();
        }
    }
    public String take() throws InterruptedException {
        String elem = null;
        synchronized (locker){
            while(size == 0){
                locker.wait();
            }
            elem = elems[head];
            head++;
            if(head >= elems.length){
                head = 0;
            }
            size--;
        }
        return elem;
    }
}
public class ThreadDemo23 {
    public static void main(String[] args) {
     MyBlockingQueue1 queue1 = new MyBlockingQueue1(1000);
     Thread t1 = new Thread(() ->{
        int n = 0;
        while(true){
            try {
                queue1.put(n + "");
                System.out.println("生产了"+n);
                n++;
                Thread.sleep(200);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
     });
     Thread t2 = new Thread(() ->{
        while(true){
            try{
                String n = queue1.take();
                System.out.println("消费了"+n);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
     });
     t1.start();
     t2.start();
    }
}
